package com.unionfind;

/**
 * @Author: tgy
 * @Date: 2020-10-20 09:34
 */
public abstract class AbstractUnionFind  {

    protected int[] parents;

    public AbstractUnionFind(int capacity) {

        if (capacity < 0) {

            capacity = 16;
        }

        this.parents = new int[capacity];

        /**
         * 初始化，自己指向自己
         */
        for (int i = 0; i < this.parents.length; i++) {

            this.parents[i] = i;
        }

    }

    /**
     * 通过v获取所属集合的跟节点
     * @param v 起始元素
     * @return
     */
    protected abstract int find(int v);

    /**
     * 合并两个集合
     * @param v1
     * @param v2
     */
    protected abstract void union(int v1,int v2);


    public boolean isSame(int v1, int v2) {

        return find(v1) == find(v2);
    }


    protected void checkV(int v) {

        if (v < 0 || v >= this.parents.length) {

            throw new IndexOutOfBoundsException(v + "超出边界");
        }
    }
}
